package com.xixi.demo02.servlet;

import com.xixi.demo02.model.User;
import com.xixi.demo02.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//建立完index.jsp登录页面，进行第二步的servlet
@WebServlet(name = "LoginServlet",urlPatterns = "/index")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//第一步就是获取请求的用户名和密码的信息并打印出来  getParameter是ServletRequest接口的方法。以字符串的形式请求参数的值，若参数不存在则返回空值
        String userName=request.getParameter("userName");
        System.out.println("获取的用户名是："+userName);
        String password=request.getParameter("password");
        System.out.println("获取到的密码是："+password);
//以上写完测试一下获取到数据没有
        User user=new User(userName,password);
        request.getSession().setAttribute("user",user);
       /* response.sendRedirect("login.jsp");*/
        response.sendRedirect("manage.jsp");
        //以上这部分实现的是重定向，将登录页面跳转到另一个页面上去

        UserService userService=new UserService();
        User user1=userService.userLoginService(new User(userName,password));
        if(null==user1){
            System.out.println("获取账号和密码 错误");
          /*  request.setAttribute("error","登录失败，用户名或者密码错");
            //getRequestDispatcher 请求转发和请求包含
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            requestDispatcher.forward(request,response);*/
        }else {
            System.out.println("登录成功");
        /*    request.getSession().setAttribute("user",user1);
            Cookie userNameCookie=new Cookie("userName",userName);
            userNameCookie.setMaxAge(3600*24*7);
            response.addCookie(userNameCookie);
            response.sendRedirect("manage.jsp");*/
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //根据Servlet+JDBC技术访问数据库来讲，先请求再响应
        this.doPost(request,response);
    }
}
